import json

from django.shortcuts import render, get_object_or_404
from django.utils.decorators import method_decorator
from rest_framework import status
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, mixins

from FasterRunner import pagination
from fastrunner import models, serializers
from fastrunner.models import Report
from fastrunner.utils.decorator import request_log
from fastrunner.utils.permissions import IsBelongToProject
from FasterRunner.settings import logger


class ReportView(GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin):
    """
    测试报告视图
    """
    serializer_class = serializers.ReportSerializer
    pagination_class = pagination.MyPageNumberPagination
    permission_classes = (DjangoModelPermissions, IsBelongToProject)

    def get_queryset(self):
        project = self.request.query_params.get("project", 0)
        if self.action == 'list':
            search = self.request.query_params.get("search", "")
            if project and int(project) > 0:
                return models.Report.objects.filter(project__id=project, name__contains=search).order_by('-update_time')
            else:
                return models.Report.objects.filter(name__contains=search).order_by('-update_time')

        return models.Report.objects.all().order_by('-update_time')

    @method_decorator(request_log(level='INFO'))
    def destroy(self, request, *args, **kwargs):
        if kwargs.get('pk') and int(kwargs['pk']) != -1:
            instance = self.get_object()
            self.perform_destroy(instance)
        elif request.data:
            for content in request.data:
                self.kwargs['pk'] = content['id']
                instance = self.get_object()
                self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    @method_decorator(request_log(level='INFO'))
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        report_detail = models.ReportDetail.objects.get(report=instance)
        summary = json.loads(report_detail.summary, encoding="utf-8")
        summary["html_report_name"] = instance.name
        logger.info(f"summary:{summary}")

        return render(request,'report_template.html', summary)
